﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using CustomsSystem.BLL;
using Maticsoft.Common;
using Microsoft.Win32;
using Maticsoft.Model;

namespace WEB.T_document
{
    public partial class excel_docment : System.Web.UI.Page
    {
        //声明一个Dictionary（并将其表明为ViewState属性），
        //其中Key值（string）代表的ID（数据库中的主键），Value值（bool）表示该行的CheckBox是否选中
        Dictionary<string, bool> docDic
        {
            get
            {
                return (ViewState["docdic"] != null) ? (Dictionary<string, bool>)ViewState["docdic"] : null;
            }
            set
            {
                ViewState["docdic"] = value;
            }
        }

        public DataSet ds;
        DataTable dt = new DataTable();
        DocumentManage bll = new DocumentManage();
        DocDataToExcel dataToExcel = new DocDataToExcel();
        PageRecord pr = new PageRecord();
        info_documentMastert DM = new info_documentMastert();
        protected void Page_Load(object sender, EventArgs e)
        {
            //实现分页，不能只执行一次
            ds = bll.GetView("");
            gvDocument.DataSource = ds;
            //绑定数据
            if (!IsPostBack)
            {
                docDic = pr. InitializeUsersDic(ds.Tables[0]);
                this.tbTimestart.Attributes.Add("onClick", "new WdatePicker()");
                this.tbTimestop.Attributes.Add("onClick", "new WdatePicker()");
                gvDocument.DataBind();

                DropDownList1.DataSource = DM.GetAllList();
                DropDownList1.DataTextField = "docViewName";
                DropDownList1.DataValueField = "docViewID";
                DropDownList1.DataBind();

                if (DropDownList1.Items.Count == 0)
                {
                    MessageBox.ShowAndRedirect(this, "没有单证模板，请联系管理人", "/workflow/workflowview.aspx");
                }
            }
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btExcel_Click(object sender, EventArgs e)
        {

            for (int i=1; i < gvDocument.Rows.Count; i++)
            {
                if (gvDocument.Rows[i].Cells[2].Text != gvDocument.Rows[i - 1].Cells[2].Text)
                {
                    MessageBox.Show(this,"请先确定页面客户是唯一的");
                    return;
                }
            }

                //记录页面的CheckBox的状态
                pr.RememberOldValues(docDic, gvDocument, "cbDoc");
            //取得列名
            foreach (DataColumn dc in ds.Tables[0].Columns)
            {
                dt.Columns.Add(dc.ColumnName,dc.DataType);
            }
            //读取数据
            for (int i = 0; i < ds.Tables[0].Rows.Count;i++ )
            {
                object[] arrdr = new object[ds.Tables[0].Columns.Count];

                if (docDic[ds.Tables[0].Rows[i][0].ToString()])
                {
                    ds.Tables[0].Rows[i].ItemArray.CopyTo(arrdr, 0);
                    dt.Rows.Add(arrdr); 
                }
            }
            //判断是否为空
            if (dt.Rows.Count == 0)
            {
                //没有选择的提示
                gvDocument.AllowPaging = true;
                MessageBox.Show(this, "请选择要导出excel的列");
                return;
            }
            else
            {
                //生成excel
                string FilePath = Server.MapPath("~/document/Excel/");
                string file = dataToExcel.OutputExcel(dt,DropDownList1.SelectedValue, "代报关单证移交情况表", FilePath);
                DownloadFile(file);
                return;
                //System.Diagnostics.Process.Start(FilePath);//打开文件夹
            }
            CustomsSystem.Model.document modeld = new CustomsSystem.Model.document();
        }
        /// <summary>
        /// 取得dt
        /// </summary>
        /// <returns></returns>
        public DataTable Getdatable(string user)
        {

            //通过sheetID取得dt
            dt = bll.GetView(user).Tables[0];
            return dt;
        }

        protected void btquery_Click(object sender, EventArgs e)
        {
            int Index = ddlQuery.SelectedIndex;
            string Query = ddlQuery.SelectedValue;
            string QueryText = tbQuery.Text.Trim();
            //搜索的整个过程
            string sql = "";//为空的时候，默认搜索全部
            string datekai = "";
            string datemo = "";
            #region
            //if (QueryText != "")//判断下拉列表的文本框是否为空
            //{
            //    //下拉列表的判断
            //    switch (Index)
            //    {
            //            //委托单查询只能为数字，如果不是数字的话转为0，就查不到数据，不会报错
            //        case 0: if (!PageValidate.IsNumber(QueryText)) QueryText = "0"; sql = sql + " and a." + Query + " = '" + QueryText + "'"; break;
            //        case 1: sql = sql + " and " + Query + " = '" + QueryText + "'"; break;
            //        default: sql = sql + " and " + Query + " LIKE '%" + QueryText + "%'"; break;
            //    }
            //}
            ////日期搜索的判断
            //if (tbTimestart.Text!= "")
            //{ 
            //    //日期截止时间为空的时候，默认为现在的时间
            //    if(tbTimestop.Text=="")
            //    {
            //        DateTime timeStop = DateTime.Now;
            //        sql = sql + " and clearanceDate between '" + tbTimestart.Text + "' and '" + timeStop + "'";
            //    }
            //    else
            //    {
            //        sql = sql + " and clearanceDate between '" + tbTimestart.Text + "' and '" + tbTimestop.Text + "'";
            //    }
            //}
            #endregion
            //重新绑定数据库
            if (tbQuery.Text != "")
            {
                sql = sql + " b.CustomerName like '%" + tbQuery.Text + "%'";
            }
            else
            {
                sql = sql+"";
            }
            if (tbTimestart.Text != "")
            {
                datekai = "and a.clearanceDate>='" + tbTimestart.Text + "'";
            }
            else
            {
                datekai = "";
            }
            if (tbTimestop.Text != "")
            {
                datemo = "and a.clearanceDate<='" + tbTimestop.Text + "'";
            }
            else
            {
                datemo = "";
            }

            ds= bll.GetView(sql+datekai+datemo);
            gvDocument.DataSource = ds;
            gvDocument.DataBind();
        }
        //// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filename">文件物理地址</param>
        protected void DownloadFile(string file)
        {
            string filename = "/document/Excel/" + file;
            int intStart = filename.LastIndexOf(@"\") + 1;
            string saveFileName = filename.Substring(intStart, filename.Length - intStart);

            System.IO.FileInfo fi = new System.IO.FileInfo(filename);
            string fileextname = fi.Extension;
            string DEFAULT_CONTENT_TYPE = "application/unknown";
            RegistryKey regkey, fileextkey;
            string filecontenttype;
            try
            {
                regkey = Registry.ClassesRoot;
                fileextkey = regkey.OpenSubKey(fileextname);
                filecontenttype = fileextkey.GetValue("Content Type", DEFAULT_CONTENT_TYPE).ToString();
            }
            catch
            {
                filecontenttype = DEFAULT_CONTENT_TYPE;
            }
            Response.Clear();
            Response.Charset = "gb2312";
            Response.Buffer = true;
            this.EnableViewState = false;
            Response.ContentEncoding = System.Text.Encoding.Default;
            //对文件进行编码，防止下载名出现乱码
            string encodefileName = System.Web.HttpUtility.UrlEncode(file, System.Text.Encoding.UTF8);

            Response.AppendHeader("Content-Disposition", "attachment;filename=" + encodefileName);
            Response.ContentType = filecontenttype;

            Response.WriteFile(filename);
            Response.Flush();
            Response.Close();

            Response.End();

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvDocument_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //记录原来分页面的所有CheckBox的状态
            pr.RememberOldValues(docDic, gvDocument,"cbDoc");
            gvDocument.PageIndex = e.NewPageIndex;
            gvDocument.DataBind();
            //重构当前选中页面的CheckBox的状态
            pr.RePopulateValues(docDic, gvDocument,"cbDoc");
                
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("modelView.aspx");
        }


        //自动检索客户
        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static string[] GetCustomersName(string prefixText, int count)
        {
            CustomerManage cusManage = new CustomerManage();
            List<string> strArray = new List<string>();
            //string[] strArray = { "中国石油公司","中顺洁柔","中山技术",
            //"捷达捷达捷达达","时代复分","幅度为爱"};
            List<CustomsSystem.Model.Customer> cusList = cusManage.GetModelList("");
            foreach (CustomsSystem.Model.Customer aCus in cusList)
            {
                strArray.Add(aCus.CustomerName);
            }
            return (from m in strArray
                    where m.Contains(prefixText)
                    select m).Take(count).ToArray();
        }
        #region
        //protected void gvDocument_DataBound(object sender, EventArgs e)
        //{
        //    for (int i = 0; i < gvDocument.Rows.Count; i++)
        //    {
        //        if (Convert.ToInt32( gvDocument.Rows[i].Cells[9].Text) == 0)
        //        {
        //            gvDocument.Rows[i].Cells[9].Text = "否";
        //        }
        //        else
        //        {
        //            gvDocument.Rows[i].Cells[9].Text = "是";
        //        }

        //    }
        //}
        #endregion
    }
}